How can I get the current date and time in PHP?

by lily.simonis , in category: PHP , 2 years ago

How can I get the current date and time in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by laury_ullrich , 2 years ago

@lily.simonis There are multiple ways to do that. You can use built-in php function time(), example:


1
2
3
4
5
6
<?php

$date = date('H:i:s', time());

// 19:05:59
echo $date;


You can use DateTime object as well to get the current date and time, example:


1
2
3
4
5
6
<?php

$dateTime = new DateTime('now');

// 19:05:59
echo $dateTime->format('H:i:s');
by porter.bins , a year ago

@lily.simonis 

To get the current date and time in PHP, you can use the date function. Here's an example of how you can use it:

1
2
$currentDateTime = date('Y-m-d H:i:s');
echo $currentDateTime;


This will output the current date and time in the format YYYY-MM-DD HH:MM:SS. For example, if the current date and time is January 6th, 2023 at 5:23pm, the output would be 2023-01-06 17:23:00.


You can use different format strings to get the date and time in different formats. For example, you can use 'Y-m-d' to get the current date in the format YYYY-MM-DD, or you can use 'h:i:s A' to get the current time in the format hh:mm:ss AM/PM. You can find a full list of format strings in the PHP documentation for the date function: http://php.net/manual/en/function.date.php